package com.gzdict.common.net

import com.drake.net.exception.NetSocketTimeoutException
import com.drake.net.exception.ResponseException
import org.json.JSONException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException


object ExceptionEngine {
    // http 请求异常
    private const val SERVER_ERROR = 400
    private const val UNAUTHORIZED = 401
    private const val FORBIDDEN = 403
    private const val NOT_FOUND = 404
    private const val REQUEST_TIMEOUT = 408
    private const val INTERNAL_SERVER_ERROR = 500
    private const val GATEWAY_ERROR = 502
    private const val SERVICE_UNAVAILABLE = 503
    private const val GETWAY_TIMEOUT = 504
    fun handleException(e: Throwable): String {
        when {
            e is ResponseException ->
                return when (e.response.code) {
                    UNAUTHORIZED -> "操作未授权"
                    FORBIDDEN -> "请求被拒绝"
                    NOT_FOUND -> "资源不存在"
                    REQUEST_TIMEOUT -> "服务器执行超时"
                    INTERNAL_SERVER_ERROR -> "服务器内部错误"
                    GATEWAY_ERROR -> "网关错误"
                    SERVICE_UNAVAILABLE -> "服务器不可用"
                    GETWAY_TIMEOUT -> "网关超时"
                    SERVER_ERROR -> "网络错误"
                    else -> "网络错误"
                }
            else -> {
                return when (e) {
                    is JSONException -> "Json异常"
                    is com.alibaba.fastjson.JSONException -> "Json异常"
                    is ConnectException -> "连接失败"
                    is SocketTimeoutException -> "连接超时"
                    is UnknownHostException -> "网络不可用或服务器异常"
                    is NetSocketTimeoutException -> "网络不可用或服务器异常"
                    else -> ""
                }
            }
        }
    }
}
